home *** CD-ROM | disk | FTP | other *** search
/ Aminet 3 / Aminet 3 - July 1994.iso / Aminet / mus / misc / mpegaudio.lha / mpegaudio / musicout.c < prev    next >
C/C++ Source or Header  |  1994-03-21  |  18KB  |  463 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. musicout.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 3.9                                                        *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers                comment                        *
  14.  * 2/25/91  Douglas Wong        start of version 1.0 records          *
  15.  * 3/06/91  Douglas Wong        rename setup.h to dedef.h             *
  16.  *                              removed extraneous variables          *
  17.  *                              removed window_samples (now part of   *
  18.  *                              filter_samples)                       *
  19.  * 3/07/91  Davis Pan           changed output file to "codmusic"     *
  20.  * 5/10/91  Vish (PRISM)        Ported to Macintosh and Unix.         *
  21.  *                              Incorporated new "out_fifo()" which   *
  22.  *                              writes out last incomplete buffer.    *
  23.  *                              Incorporated all AIFF routines which  *
  24.  *                              are also compatible with SUN.         *
  25.  *                              Incorporated user interface for       *
  26.  *                              specifying sound file names.          *
  27.  *                              Also incorporated user interface for  *
  28.  *                              writing AIFF compatible sound files.  *
  29.  * 27jun91  dpwe (Aware)        Added musicout and &sample_frames as  *
  30.  *                              args to out_fifo (were glob refs).    *
  31.  *                              Used new 'frame_params' struct.       *
  32.  *                              Clean,simplify, track clipped output  *
  33.  *                              and total bits/frame received.        *
  34.  * 7/10/91  Earle Jennings      changed to floats to FLOAT            *
  35.  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
  36.  *          Don H. Lee,                                               *
  37.  *          Peter W. Farrett                                          *
  38.  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
  39.  *                              newly introduced functions are        *
  40.  *                              buffer_CRC and recover_CRC_error      *
  41.  *                              Additions and revisions are marked    *
  42.  *                              with "dhl" for clarity                *
  43.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  44.  *                              important fixes involved changing     *
  45.  *                              16-bit ints to long or unsigned in    *
  46.  *                              bit alloc routines for quant of 65535 *
  47.  *                              and passing proper function args.     *
  48.  *                              Removed "Other Joint Stereo" option   *
  49.  *                              and made bitrate be total channel     *
  50.  *                              bitrate, irrespective of the mode.    *
  51.  *                              Fixed many small bugs & reorganized.  *
  52.  *19 aug 92 Soren H. Nielsen    Changed MS-DOS file name extensions.  *
  53.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  54.  *         Daniel Lauzon, and                                         *
  55.  *         Bill Truerniet                                             *
  56.  **********************************************************************/
  57.  
  58. #include        "common.h"
  59. #include        "decoder.h"
  60.  
  61. #ifdef UNIX
  62. #include <time.h>
  63. #endif
  64.  
  65. /********************************************************************
  66. /*
  67. /*        This part contains the MPEG I decoder for Layers I & II.
  68. /*
  69. /*********************************************************************/
  70.  
  71. /****************************************************************
  72. /*
  73. /*        For MS-DOS user (Turbo c) change all instance of malloc
  74. /*        to _farmalloc and free to _farfree. Compiler model hugh
  75. /*        Also make sure all the pointer specified are changed to far.
  76. /*
  77. /*****************************************************************/
  78.  
  79. /*********************************************************************
  80. /*
  81. /* Core of the Layer II decoder.  Default layer is Layer II.
  82. /*
  83. /*********************************************************************/
  84.  
  85. /* Global variable definitions for "musicout.c" */
  86.  
  87. char *programName;
  88.  
  89. /* Implementations */
  90.  
  91. main(argc, argv)
  92. int argc;
  93. char **argv;
  94. {
  95. typedef short PCM[2][3][SBLIMIT];
  96.     PCM FAR *pcm_sample;
  97. typedef unsigned int SAM[2][3][SBLIMIT];
  98.     SAM FAR *sample;
  99. typedef double FRA[2][3][SBLIMIT];
  100.     FRA FAR *fraction;
  101. typedef double VE[2][HAN_SIZE];
  102.     VE FAR *w;
  103.  
  104.     Bit_stream_struc  bs;
  105.     frame_params      fr_ps;
  106.     layer             info;
  107.     FILE              *musicout;
  108.     unsigned long     sample_frames;
  109.  
  110.     int               i, j, k, stereo, done=FALSE, clip, sync;
  111.     int               error_protection, crc_error_count, total_error_count;
  112.     unsigned int      old_crc, new_crc;
  113.     unsigned int      bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT],
  114.                       scale_index[2][3][SBLIMIT];
  115.     unsigned long     bitsPerSlot, samplesPerFrame, frameNum = 0;
  116.     unsigned long     frameBits, gotBits = 0;
  117.     IFF_AIFF          pcm_aiff_data;
  118.     char              encoded_file_name[MAX_NAME_SIZE];
  119.     char              decoded_file_name[MAX_NAME_SIZE];
  120.     char              t[50];
  121.     int               need_aiff;
  122.     int topSb = 0;
  123.  
  124. #ifdef UNIX
  125.     clock_t time_to_decode = clock();
  126. #endif
  127.  
  128. #ifdef  MACINTOSH
  129.     console_options.nrows = MAC_WINDOW_SIZE;
  130.     argc = ccommand(&argv);
  131. #endif
  132.  
  133.     /* Most large variables are declared dynamically to ensure
  134.        compatibility with smaller machines */
  135.  
  136.     pcm_sample = (PCM FAR *) mem_alloc((long) sizeof(PCM), "PCM Samp");
  137.     sample = (SAM FAR *) mem_alloc((long) sizeof(SAM), "Sample");
  138.     fraction = (FRA FAR *) mem_alloc((long) sizeof(FRA), "fraction");
  139.     w = (VE FAR *) mem_alloc((long) sizeof(VE), "w");
  140.  
  141.     fr_ps.header = &info;
  142.     fr_ps.tab_num = -1;                /* no table loaded */
  143.     fr_ps.alloc = NULL;
  144.     for (i=0;i<HAN_SIZE;i++) for (j=0;j<2;j++) (*w)[j][i] = 0.0;
  145.  
  146.     programName = argv[0];
  147.     if(argc==1) {        /* no command line args -> interact */
  148.        do {
  149.           printf ("Enter encoded file name <required>: ");
  150.           gets (encoded_file_name);
  151.           if (encoded_file_name[0] == NULL_CHAR)
  152.              printf ("Encoded file name is required. \n");
  153.        } while (encoded_file_name[0] == NULL_CHAR);
  154.        printf (">>> Encoded file name is: %s \n", encoded_file_name);
  155. #ifdef  MS_DOS
  156.        printf ("Enter MPEG decoded file name <%s>: ",
  157.                new_ext(encoded_file_name, DFLT_OPEXT)); /* 92-08-19 shn */
  158. #else
  159.        printf ("Enter MPEG decoded file name <%s%s>: ", encoded_file_name,
  160.                DFLT_OPEXT);
  161. #endif
  162.        gets (decoded_file_name);
  163.        if (decoded_file_name[0] == NULL_CHAR) {
  164. #ifdef  MS_DOS
  165.            /* replace old extension with new one, 92-08-19 shn */
  166.            strcpy(decoded_file_name,new_ext(encoded_file_name, DFLT_OPEXT));
  167. #else
  168.            strcat (strcpy(decoded_file_name, encoded_file_name), DFLT_OPEXT);
  169. #endif
  170.        }
  171.        printf (">>> MPEG decoded file name is: %s \n", decoded_file_name);
  172.  
  173.        printf(
  174.           "Do you wish to write an AIFF compatible sound file ? (y/<n>) : ");
  175.        gets(t);
  176.        if (*t == 'y' || *t == 'Y') need_aiff = TRUE;
  177.        else                        need_aiff = FALSE;
  178.        if (need_aiff)
  179.             printf(">>> An AIFF compatible sound file will be written\n");
  180.        else printf(">>> A non-headered PCM sound file will be written\n");
  181.  
  182.        printf(
  183.           "Do you wish to exit (last chance before decoding) ? (y/<n>) : ");
  184.        gets(t);
  185.        if (*t == 'y' || *t == 'Y') exit(0);
  186.     }
  187.     else {        /* interpret CL Args */
  188.        int i=0, err=0;
  189.  
  190.        need_aiff = FALSE;
  191.        encoded_file_name[0] = '\0';
  192.        decoded_file_name[0] = '\0';
  193.  
  194.        while(++i<argc && err == 0) {
  195.           char c, *token, *arg, *nextArg;
  196.           int  argUsed;
  197.  
  198.           token = argv[i];
  199.           if(*token++ == '-') {
  200.              if(i+1 < argc) nextArg = argv[i+1];
  201.              else           nextArg = "";
  202.              argUsed = 0;
  203.              while(c = *token++) {
  204.                 if(*token /* NumericQ(token) */) arg = token;
  205.                 else                             arg = nextArg;
  206.                 switch(c) {
  207.                    case 's':  topSb = atoi(arg); argUsed = 1;
  208.                       if(topSb<1 || topSb>SBLIMIT) {
  209.                          fprintf(stderr, "%s: -s band %s not %d..%d\n",
  210.                                  programName, arg, 1, SBLIMIT);
  211.                          err = 1;
  212.                       }
  213.                       break;
  214.                    case 'A':  need_aiff = TRUE; break;
  215.                    default:   fprintf(stderr,"%s: unrecognized option %c\n",
  216.                                       programName, c);
  217.                       err = 1; break;
  218.                 }
  219.                 if(argUsed) {
  220.                    if(arg == token) token = ""; /* no more from token */
  221.                    else             ++i; /* skip arg we used */
  222.                    arg = ""; argUsed = 0;
  223.                 }
  224.              }
  225.           }
  226.           else {
  227.              if(encoded_file_name[0] == '\0')
  228.                 strcpy(encoded_file_name, argv[i]);
  229.              else
  230.                 if(decoded_file_name[0] == '\0')
  231.                    strcpy(decoded_file_name, argv[i]);
  232.                 else {
  233.                    fprintf(stderr,
  234.                            "%s: excess arg %s\n", programName, argv[i]);
  235.                    err = 1;
  236.                 }
  237.           }
  238.        }
  239.  
  240.        if(err || encoded_file_name[0] == '\0') usage();  /* never returns */
  241.  
  242.        if(decoded_file_name[0] == '\0') {
  243.           strcpy(decoded_file_name, encoded_file_name);
  244.           strcat(decoded_file_name, DFLT_OPEXT);
  245.        }
  246.  
  247.     }
  248.     /* report results of dialog / command line */
  249.     printf("Input file = '%s'  output file = '%s'\n",
  250.            encoded_file_name, decoded_file_name);
  251.     if(need_aiff) printf("Output file written in AIFF format\n");
  252.  
  253.     if(strcmp(decoded_file_name,"stdout") == 0) musicout = stdout;
  254.     else {
  255.          if ((musicout = fopen(decoded_file_name, "w+b")) == NULL) {
  256.             printf ("Could not create \"%s\".\n", decoded_file_name);
  257.             exit(1);
  258.          }
  259.     }
  260.  
  261.     open_bit_stream_r(&bs, encoded_file_name, BUFFER_SIZE);
  262.  
  263.     if (need_aiff)
  264.        if (aiff_seek_to_sound_data(musicout) == -1) {
  265.           printf("Could not seek to PCM sound data in \"%s\".\n",
  266.                  decoded_file_name);
  267.           exit(1);
  268.        }
  269.  
  270.     sample_frames = 0;
  271.  
  272.     while (!end_bs(&bs)) {
  273.  
  274.        sync = seek_sync(&bs, SYNC_WORD, SYNC_WORD_LNGTH);
  275.        frameBits = sstell(&bs) - gotBits;
  276.        if(frameNum > 0)        /* don't want to print on 1st loop; no lay */
  277.           if(frameBits%bitsPerSlot)
  278.              fprintf(stderr,"Got %ld bits = %ld slots plus %ld\n",
  279.                      frameBits, frameBits/bitsPerSlot, frameBits%bitsPerSlot);
  280.        gotBits += frameBits;
  281.  
  282.        if (!sync) {
  283.           printf("Frame cannot be located\n");
  284.           printf("Input stream may be empty\n");
  285.           done = TRUE;
  286.           /* finally write out the buffer */
  287.           if (info.lay == 2) out_fifo(*pcm_sample, 3, &fr_ps, done,
  288.                                       musicout, &sample_frames);
  289.           else               out_fifo(*pcm_sample, 1, &fr_ps, done,
  290.                                       musicout, &sample_frames);
  291.           break;
  292.        }
  293.  
  294.        decode_info(&bs, &fr_ps);
  295.        hdr_to_frps(&fr_ps);
  296.        stereo = fr_ps.stereo;
  297.        error_protection = info.error_protection;
  298.        crc_error_count = 0;
  299.        total_error_count = 0;
  300.        if(frameNum == 0) WriteHdr(&fr_ps, stdout);  /* printout layer/mode */
  301.  
  302.        fprintf(stderr, "{%4lu}\r", frameNum++); fflush(stderr);
  303.        if (error_protection) buffer_CRC(&bs, &old_crc);
  304.  
  305.        switch (info.lay) {
  306.  
  307.           case 1: {
  308.              bitsPerSlot = 32;        samplesPerFrame = 384;
  309.              I_decode_bitalloc(&bs,bit_alloc,&fr_ps);
  310.              I_decode_scale(&bs, bit_alloc, scale_index, &fr_ps);
  311.  
  312.              if (error_protection) {
  313.                 I_CRC_calc(&fr_ps, bit_alloc, &new_crc);
  314.                 if (new_crc != old_crc) {
  315.                    crc_error_count++;
  316.                    total_error_count++;
  317.                    recover_CRC_error(*pcm_sample, crc_error_count,
  318.                                      &fr_ps, musicout, &sample_frames);
  319.                    break;
  320.                 }
  321.                 else crc_error_count = 0;
  322.              }
  323.  
  324.              clip = 0;
  325.              for (i=0;i<SCALE_BLOCK;i++) {
  326.                 I_buffer_sample(&bs,(*sample),bit_alloc,&fr_ps);
  327.                 I_dequantize_sample(*sample,*fraction,bit_alloc,&fr_ps);
  328.                 I_denormalize_sample((*fraction),scale_index,&fr_ps);
  329.                 if(topSb>0)        /* clear channels to 0 */
  330.                    for(j=topSb; j<fr_ps.sblimit; ++j)
  331.                       for(k=0; k<stereo; ++k)
  332.                          (*fraction)[k][0][j] = 0;
  333.  
  334.                 for (j=0;j<stereo;j++) {
  335.                    clip += SubBandSynthesis (&((*fraction)[j][0][0]), j,
  336.                                              &((*pcm_sample)[j][0][0]));
  337.                 }
  338.                 out_fifo(*pcm_sample, 1, &fr_ps, done,
  339.                          musicout, &sample_frames);
  340.              }
  341.              if(clip > 0) printf("%d output samples clipped\n", clip);
  342.              break;
  343.           }
  344.  
  345.           case 2: {
  346.              bitsPerSlot = 8;        samplesPerFrame = 1152;
  347.              II_decode_bitalloc(&bs, bit_alloc, &fr_ps);
  348.              II_decode_scale(&bs, scfsi, bit_alloc, scale_index, &fr_ps);
  349.  
  350.              if (error_protection) { 
  351.                 II_CRC_calc(&fr_ps, bit_alloc, scfsi, &new_crc);
  352.                 if (new_crc != old_crc) {
  353.                    crc_error_count++;
  354.                    total_error_count++;
  355.                    recover_CRC_error(*pcm_sample, crc_error_count,
  356.                                      &fr_ps, musicout, &sample_frames);
  357.                    break;
  358.                 }
  359.                 else crc_error_count = 0;
  360.              }
  361.  
  362.              clip = 0;
  363.              for (i=0;i<SCALE_BLOCK;i++) {
  364.                 II_buffer_sample(&bs,(*sample),bit_alloc,&fr_ps);
  365.                 II_dequantize_sample((*sample),bit_alloc,(*fraction),&fr_ps);
  366.                 II_denormalize_sample((*fraction),scale_index,&fr_ps,i>>2);
  367.  
  368.                 if(topSb>0)        /* debug : clear channels to 0 */
  369.                    for(j=topSb; j<fr_ps.sblimit; ++j)
  370.                       for(k=0; k<stereo; ++k)
  371.                          (*fraction)[k][0][j] =
  372.                          (*fraction)[k][1][j] =
  373.                          (*fraction)[k][2][j] = 0;
  374.  
  375.                 for (j=0;j<3;j++) for (k=0;k<stereo;k++) {
  376.                    clip += SubBandSynthesis (&((*fraction)[k][j][0]), k,
  377.                                              &((*pcm_sample)[k][j][0]));
  378.                 }
  379.                 out_fifo(*pcm_sample, 3, &fr_ps, done, musicout,
  380.                          &sample_frames);
  381.              }
  382.              if(clip > 0) printf("%d samples clipped\n", clip);
  383.              break;
  384.           }
  385.  
  386.        }
  387.  
  388.     }
  389.  
  390.     if (need_aiff) {
  391.        pcm_aiff_data.numChannels       = stereo;
  392.        pcm_aiff_data.numSampleFrames   = sample_frames;
  393.        pcm_aiff_data.sampleSize        = 16;
  394.        pcm_aiff_data.sampleRate        = s_freq[info.sampling_frequency]*1000;
  395. #ifdef IFF_LONG       
  396.        pcm_aiff_data.sampleType        = IFF_ID_SSND;
  397. #else
  398.        strncpy(&pcm_aiff_data.sampleType,IFF_ID_SSND,4);
  399. #endif
  400.        pcm_aiff_data.blkAlgn.offset    = 0;
  401.        pcm_aiff_data.blkAlgn.blockSize = 0;
  402.  
  403.        if (aiff_write_headers(musicout, &pcm_aiff_data) == -1) {
  404.           printf("Could not write AIFF headers to \"%s\"\n",
  405.                  decoded_file_name);
  406.           exit(2);
  407.        }
  408.     }
  409.  
  410.     printf("Avg slots/frame = %.3f; b/smp = %.2f; br = %.3f kbps\n",
  411.            (FLOAT) gotBits / (frameNum * bitsPerSlot),
  412.            (FLOAT) gotBits / (frameNum * samplesPerFrame),
  413.            (FLOAT) gotBits / (frameNum * samplesPerFrame) *
  414.            s_freq[info.sampling_frequency]);
  415.  
  416.     close_bit_stream_r(&bs);
  417.     fclose(musicout);
  418.  
  419.     /* for the correct AIFF header information */
  420.     /*             on the Macintosh            */
  421.     /* the file type and the file creator for  */
  422.     /* Macintosh compatible Digidesign is set  */
  423.  
  424. #ifdef  MACINTOSH
  425.     if (need_aiff) set_mac_file_attr(decoded_file_name, VOL_REF_NUM,
  426.                                      CREATR_DEC_AIFF, FILTYP_DEC_AIFF);
  427.     else           set_mac_file_attr(decoded_file_name, VOL_REF_NUM,
  428.                                      CREATR_DEC_BNRY, FILTYP_DEC_BNRY);
  429. #endif
  430.  
  431.     printf("Decoding of \"%s\" is finished\n", encoded_file_name);
  432.     printf("The decoded PCM output file name is \"%s\"\n", decoded_file_name);
  433.     if (need_aiff)
  434.        printf("\"%s\" has been written with AIFF header information\n",
  435.               decoded_file_name);
  436.  
  437. #ifdef UNIX
  438.     time_to_decode = clock()-time_to_decode;
  439.  
  440.     printf("Total time used to decode the stream was %.2f secs.\n",
  441.     (float)time_to_decode/CLK_TCK);
  442. #endif
  443.  
  444.  
  445.     exit( 0 );
  446. }
  447.  
  448. static void usage()  /* print syntax & exit */
  449. {
  450.    fprintf(stderr,
  451.       "usage: %s                         queries for all arguments, or\n",
  452.        programName);
  453.    fprintf(stderr,
  454.       "       %s [-A][-s sb] inputBS [outPCM]\n", programName);
  455.    fprintf(stderr,"where\n");
  456.    fprintf(stderr," -A       write an AIFF output PCM sound file\n");
  457.    fprintf(stderr," -s sb    resynth only up to this sb (debugging only)\n");
  458.    fprintf(stderr," inputBS  input bit stream of encoded audio\n");
  459.    fprintf(stderr," outPCM   output PCM sound file (dflt inName+%s)\n",
  460.            DFLT_OPEXT);
  461.    exit(1);
  462. }
  463.